package com.cn.shuangzi.common;

import android.content.Context;
import android.os.Looper;
import android.text.TextUtils;

import com.cn.shuangzi.SZApp;
import com.cn.shuangzi.SZManager;
import com.cn.shuangzi.util.SZToast;
import com.cn.shuangzi.util.SZUtil;
import com.taobao.accs.ACCSClient;
import com.taobao.accs.AccsClientConfig;
import com.taobao.agoo.TaobaoRegister;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.commonsdk.utils.UMUtils;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.MsgConstant;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageService;

import org.android.agoo.honor.HonorRegister;
import org.android.agoo.huawei.HuaWeiRegister;
import org.android.agoo.oppo.OppoRegister;
import org.android.agoo.vivo.VivoRegister;
import org.android.agoo.xiaomi.MiPushRegistar;

/**
 * PushSDK集成帮助类
 */
public class UMPushHelper {

    private static PushAgent pushAgent;

    /**
     * 预初始化，已添加子进程中初始化sdk。
     * 使用场景：用户未同意隐私政策协议授权时，延迟初始化
     *
     */
    public static void preInit() {
        try {
            //解决推送消息显示乱码的问题
            AccsClientConfig.Builder builder = new AccsClientConfig.Builder();
            builder.setAppKey("umeng:" + SZUtil.getAppMetaDataString(SZApp.getInstance(), "UMENG_APPKEY"));
            builder.setAppSecret(SZUtil.getAppMetaDataString(SZApp.getInstance(), "UMENG_MESSAGE_SECRET"));
            builder.setTag(AccsClientConfig.DEFAULT_CONFIGTAG);
            ACCSClient.init(SZApp.getInstance(), builder.build());
            TaobaoRegister.setAccsConfigTag(SZApp.getInstance(), AccsClientConfig.DEFAULT_CONFIGTAG);
        } catch (Exception e) {
            e.printStackTrace();
        }
        UMConfigure.preInit(SZApp.getInstance(), SZUtil.getAppMetaDataString(SZApp.getInstance(), "UMENG_APPKEY"), SZUtil.getChannel(SZApp.getInstance()));
    }

    /**
     * 初始化。
     * 场景：用户已同意隐私政策协议授权时
     *
     */
    public static void init() {
        SZManager.getInstance().initUMConfig();
        //获取消息推送实例
        pushAgent = PushAgent.getInstance(SZApp.getInstance());
        pushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SDK_ENABLE);
        pushAgent.setNotificationPlayLights(MsgConstant.NOTIFICATION_PLAY_SDK_ENABLE);
        pushAgent.setNotificationPlayVibrate(MsgConstant.NOTIFICATION_PLAY_SDK_ENABLE);
        pushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SERVER);
    }

    public static <U extends UmengMessageService> void registerPush(final String userId,Class<U> pushMessageService){
        pushAgent.setPushIntentServiceClass(pushMessageService);
        //使用完全自定义处理
        pushAgent.setPushCheck(SZApp.getInstance().isDebug());
        pushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                SZUtil.saveUToken(deviceToken);
                SZUtil.log("设备 token: " + deviceToken);
                addAlias(userId);
            }

            @Override
            public void onFailure(String s, String s1) {
                SZUtil.log("注册token失败: " + s + " " + s1);
            }
        });
    }
    public static void initChannelPush(String oppoAppKey,String oppoAppSecret,String xiaomiId,String xiaomiKey) {
        HuaWeiRegister.register(SZApp.getInstance());
        if(oppoAppKey!=null&&oppoAppSecret!=null) {
            OppoRegister.register(SZApp.getInstance(), oppoAppKey, oppoAppSecret);
        }
        VivoRegister.register(SZApp.getInstance());
        if(xiaomiId!=null&&xiaomiKey!=null) {
            MiPushRegistar.register(SZApp.getInstance(), xiaomiId, xiaomiKey);
        }
        HonorRegister.register(SZApp.getInstance());
    }

    /**
     * 是否运行在主进程
     *
     * @param context 应用上下文
     * @return true: 主进程；false: 子进程
     */
    public static boolean isMainProcess(Context context) {
        return UMUtils.isMainProgress(context);
    }

    public static void addAlias(final String userId) {
        if (TextUtils.isEmpty(userId)) {
            return;
        }
        String uToken = SZUtil.getUToken();
        if (TextUtils.isEmpty(uToken)) {
            getPushAgent().register(new IUmengRegisterCallback() {
                @Override
                public void onSuccess(String deviceToken) {
                    SZUtil.saveUToken(deviceToken);
                    addAlias(userId);
                }

                @Override
                public void onFailure(String s, String s1) {
                    SZUtil.log("友盟注册失败: " + "register failed: " + s + " " + s1);
                }
            });
        } else {
            getPushAgent().addAlias(userId, SZConst.ALIAS_TYPE, new UTrack.ICallBack() {
                @Override
                public void onMessage(boolean isSuccess, String message) {
                    SZUtil.log("绑定是否成功：" + isSuccess + "|原因：" + message);
                }
            });
        }
    }

    public static void deleteAlias(String userId, final UTrack.ICallBack iCallBack) {
        getPushAgent().deleteAlias(userId, SZConst.ALIAS_TYPE, new UTrack.ICallBack() {
            @Override
            public void onMessage(boolean isSuccess, String message) {
                if (isSuccess) {
                    if (iCallBack != null) {
                        iCallBack.onMessage(true, message);
                    }
                } else {
                    if (message.contains("HttpRequestException")) {
                        if (iCallBack != null) {
                            iCallBack.onMessage(false, message);
                        }
                    } else {
                        if (iCallBack != null) {
                            iCallBack.onMessage(true, message);
                        }
                    }
                }
            }
        });
    }

    public static PushAgent getPushAgent() {
        if (pushAgent == null) {
            init();
        }
        return pushAgent;
    }
}
